package com.study.gank.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.study.gank.R
import com.study.gank.bean.GankGoods
import com.study.gank.databinding.ViewRecyclerBinding
import com.study.gank.di.component.GankGoodsModule
import com.study.gank.getMainComponent
import com.study.gank.mvp.contract.GankGoodsContract
import com.study.gank.mvp.presenter.GankGoodsPresenter
import com.study.gank.ui.activity.ImageActivity
import com.study.gank.ui.adapter.GirlAdapter
import javax.inject.Inject

class GirlFragment : BaseBindingFragment<ViewRecyclerBinding>(), GankGoodsContract.View {

    @Inject
    lateinit var mPresenter: GankGoodsPresenter
    private lateinit var mAdapter: GirlAdapter
    private val mDatas = mutableListOf<GankGoods>()
    private var mPage = 1

    override fun createDataBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): ViewRecyclerBinding {
        return ViewRecyclerBinding.inflate(inflater)
    }

    override fun initView() {
        mAdapter = GirlAdapter(mDatas)
        mContext.getMainComponent().buildGankGoodsComponent(GankGoodsModule(this)).inject(this)
        with(mBinding) {
            recyclerView.layoutManager = LinearLayoutManager(mContext)
            recyclerView.adapter = mAdapter
            mAdapter.setOnItemClickListener {
                ImageActivity.starter(
                    mContext,
                    recyclerView.findViewHolderForAdapterPosition(it)?.itemView?.findViewById(
                        R.id.iv_girl
                    ) as ImageView,
                    mDatas[it].url
                )
            }
        }
        mPresenter.getdata(mPage, GIRL)
    }

    override fun onShowData(datas: List<GankGoods>) {
        mDatas.addAll(datas)
        mAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.unSubscribe()
    }

    companion object {
        val GIRL = "GIRL"
        fun newInstance(): GirlFragment {
            val fragment = GirlFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }
}